<template>
	<div>
		<Content>
			<Form :label-width="140">
				<h1>基本信息</h1>
				<FormItem label="项目名称" required>
					<Input class="view-input" v-model="formData.spuName" placeholder="请输入项目名称"></Input>
				</FormItem>
				<FormItem label="产权所在地区" required>
					<Cascader class="view-input"  :data="regionArray" @on-change="regionSelector" :load-data="loadRegion"></Cascader>
				</FormItem>
				<FormItem label="产权详情地址">
					<Input class="view-input" placeholder="请输入产权详细地区" v-model="formData.productionPlace" />
				</FormItem>
				<FormItem label="商品分类" required>
					<Cascader class="view-input" :data="category" v-model="categoryArray" :load-data="loadData"></Cascader>
				</FormItem>
				<FormItem label="供应商" required>
					<Select class="view-input" placeholder="请选择供应商" v-model="formData.orgId" :disabled="orgFreeze">
						<Option v-for="item in seletions" :value="item.orgId" :key="item.orgId">{{item.orgName}}</Option>
					</Select>
				</FormItem>
				<FormItem label="项目图片" required>
					<template>
						<div class="demo-upload-list" v-for="(item,id) in spuUploadList" :key="id">
							<template v-if="item.status === 'finished'">
								<img :src="item.src" alt="img">
								<div class="demo-upload-list-cover">
									<Icon type="ios-eye-outline" @click.native="handleView(item.src)" title="预览"></Icon>
									<Icon type="ios-trash-outline" @click.native="handleRemove(id)" title="删除"></Icon>
								</div>
							</template>
							<template v-else>
								<Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
							</template>
						</div>
						<Upload ref="spu_upload"
							:show-upload-list="false"
							:on-success="onUploadSuccess"
							:format="['jpg','jpeg','png']"
							:max-size="4096"
							:on-format-error="handleFormatError"
							:on-exceeded-size="handleMaxSize"
							:before-upload="spuHandleBeforeUpload"
							type="drag"
							name="binaryFile"
							:headers="uploadHeader"
							:data="uploadParam"
							:action="uploadApi"
							style="display: inline-block;width:58px;">
							<div style="width: 58px;height:58px;line-height: 58px;">
								<Icon type="ios-camera" size="20"></Icon>
							</div>
						</Upload>
						<span style="font-size:12px;color:gray;margin-left:5px;position:relative;top:-10px">最多支持5张图片，图片尺寸建议800×800像素</span>
					</template>
				</FormItem>
			</Form>

			<Form :label-width="140" inline>
				<FormItem label="产权归属" required>
					<Select placeholder="请选择产权归属" style="width:120px" v-model="formData.propertyEntity.propertyBelong">
						<Option v-for="item in propertyBelongs" :value="item.id" :key="item.id">{{item.name}}</Option>
					</Select>
				</FormItem>
				<FormItem label="产权类型" required>
					<Select placeholder="请选择产权类型" style="width:220px" v-model="formData.propertyEntity.propertyType">
						<Option v-for="item in propertyTypes" :value="item.id" :key="item.id">{{item.name}}</Option>
					</Select>
				</FormItem>
				<FormItem label="资源锁定费(元)" required>
					<InputNumber :min="0" placeholder="请输入资源锁定费" class="view-input" v-model="skuInfo.salesPrice" />
				</FormItem>
				<FormItem label="产权交易价(元)" required>
					<InputNumber :min="0" placeholder="请输入产权交易价" class="view-input" v-model="skuInfo.aroundPrice" />
				</FormItem>
				<FormItem label="计价单位" required>
					<Input placeholder="请输入计价单位" class="view-input" v-model="skuInfo.skuUom" />
				</FormItem>
				<FormItem label="产权用途">
					<Input placeholder="请输入用途描述" class="view-input" v-model="formData.propertyEntity.purposeNotes" />
				</FormItem>
				<FormItem label="流转方式" required>
					<Select placeholder="请选择流转方式" style="width:120px" v-model="formData.propertyEntity.transferType">
						<Option v-for="item in transferTypes" :value="item.id" :key="item.id">{{item.name}}</Option>
					</Select>
				</FormItem>
				<FormItem label="产权面积" required>
					<Input placeholder="请输入面积" class="view-input" v-model="formData.propertyEntity.propertyArea"><span slot="append">m²</span></Input>
				</FormItem>
				<FormItem label="流转年限" required>
					<InputNumber :min="0" placeholder="请输入流转年限" class="view-input" v-model="formData.propertyEntity.transferLimit" />
				</FormItem>
				<FormItem label="联系人">
					<Input placeholder="请输入联系人姓名" class="view-input" v-model="formData.propertyEntity.consultUser" />
				</FormItem>
				<FormItem label="联系电话">
					<Input placeholder="请输入联系电话" class="view-input" v-model="formData.propertyEntity.consultMobile" />
				</FormItem>
				<FormItem label="带看服务费(元)">
					<InputNumber :min="0" placeholder="请输入咨询费用" class="view-input" v-model="formData.propertyEntity.consultFee" />
				</FormItem>
				<FormItem label="产权关键词">
					<Input placeholder="多个关键词请用空格分隔，如：靠海 带院子 有车位" class="view-input" style="width:500px" v-model="formData.viewLabel" />
				</FormItem>
			</Form>
			<h1>其它内容</h1>
			<template>
				<article id="editorContainer" style="margin-top:30px;margin-left:140px"></article>
			</template>
			<Form>
				<FormItem style="position:fixed;z-index:999999;bottom: 10px;right:50px">
					<Button type="primary" @click="Submit">保存</Button>
				</FormItem>
			</Form>
		</Content>
		<Modal title="View Image" v-model="visible">
			<img :src="imgName" v-if="visible" style="width: 100%">
		</Modal>
	</div>
</template>
<script>
import Dict from '../../../libs/Dict'
import E from '@/libs/SourceCodeEditor'
export default {
	name: 'GoodsCreate',
	props: {
		callbank: Function,
    seletions: Array
	},
	data() {
		return {
			propertyBelongs: Dict.propertyBelong.data,
			propertyTypes: Dict.propertyType.data,
			transferTypes: Dict.transferType.data,
			regionArray: [],
			orgFreeze: this.$store.getUser('userType') !== 9,
			skuImageUpload: [],
			uploadApi: `${env_config.upload_config.api}/agrobiz-file/v1.0/upload/single/file/binary`,
			uploadHeader: {
				'Authorization': 'Bearer ' + this.$store.getToken()
			},
			uploadParam: {
				catalog:'goods'
			},
			skuInfo: {
				inventory: 1,
				salesPrice: 0,
				systemPrice: 0
			},
			formData: {
				orgId: this.$store.getOrg('orgId'),
				orgName: this.$store.getOrg('orgName'),
				shopId: this.$store.getShop('shopId'),
				shopName: this.$store.getShop('shopName'),
				salesModel: this.$store.getShop('shopType'),
				storeId: this.$store.getWms('warehouseId'),
				warehouseName: this.$store.getWms('warehouseName'),
				regionCode: this.$store.getWms('countyCode'),
				outputRate: 0,
				inputRate: 0,
				wholesalePrice: 0.00,
				profitRate: 0,
				spuImage: null,
				spuName: null, //商品名称
				categoryId: null, //类目id
				spuType: 2, //商品类型：0 零售商品，1 批发商品，2 产权交易，3 电子卡券，4积分商品，5限时抢购
				groupId: null,
				miniBuy: 1, //多少件起售
				spuSort: 9,//排序
				spuArticle: null,
				propertyEntity: {
					propertyBelong: 0,
					propertyType: 0,
					transferType: 0,
					transferLimit: 0,
					consultFee: 0
				},
				skuList: []
			},
			imgName: null,
			visible: false,
			spuUploadList: [],
			categoryArray: [],
			category: [],
			editor: null
		}
	},
	watch: {
		categoryArray(val) {
			if(val.length > 1) {
				let index = val.length - 1
				this.formData.categoryId = val[index]
				this.formData.categoryPath = val.slice(0,-1).join('/')
			} else {
				this.formData.categoryId = val[0]
				this.formData.categoryPath = '/'
			}
		}
	},
	computed: {
		
	},
	methods: {
		Init(){
			this.getCategoryList()
			this.regionInit()
		},
		getCategoryList(){
			new this.$rest({
				service: 'agroerp-shop',
				 gateway: 'agroerp',
				url: '/v1.0/plus/category/lazy',
				query: {
					equal:{
						categoryType: 0
					}
				},
				action: (res)=>{
					if(res.data.code === 20000){
						const data = res.data.data
						this.category = data
					} else {
						this.$Notice.warning({
							title: '商品分类获取失败',
							desc: `失败原因：${res.data.msg}`
						})
					}
				}
			}).get()
		},
		loadData (item, callback) {
			item.loading = true;
			new this.$rest({
				service: 'agroerp-shop',
				gateway: 'agroerp',
				url: '/v1.0/plus/category/lazy',
				query: {
					equal: {
						categoryPid: item.value,
						categoryType: 0
					},
				},
				action: (res)=>{
					if(res.data.code === 20000){
						const data = res.data.data
						item.children = data
						item.loading = false;
                    callback();
					} else {
						this.$Notice.warning({
							title: '商品分组获取失败2',
							desc: `失败原因：${res.data.msg}`
						})
					}
				}
			}).get()
		},
		handleView(src) {
			this.$Modal.info({
				content: `<img style="width:100%" src="${src}">`,
				width: '500px',
			})
		},
		handleRemove(id) {
			this.spuUploadList.splice(id, 1)
		},
		handleFormatError(file) {
			this.$Notice.warning({
				title: '图片格式不支持',
				desc: `${file.name}图片格式不支持，请使用jpg、jpeg、png`
			})
		},
		handleMaxSize(file) {
			this.$Notice.warning({
				title: '图片过大',
				desc: `${file.name}图片大小不能超过2M`
			})
		},
		onUploadSuccess(response, file, fileList) {
			if(response.code == 20000){
				fileList.forEach(element => {
					element.src = element.response.data.protocol + element.response.data.hostName + element.response.data.filePath
				})
			} else {
				this.$Notice.warning({
					title: '上传失败',
					desc: `失败原因：${response.msg}`
				})
			}
			console.log('spuUploadList ->',this.spuUploadList)
		},
		spuHandleBeforeUpload(file) {
			window.URL = window.URL || window.webkitURL
			const check = this.spuUploadList.length < 5
			if (!check) {
				this.$Notice.warning({
					title: '最多可上传5张商品图'
				})
			}
			return check
		},
		regionSelector(value, data) {
      this.formData.propertyEntity.provinceCode = data[0].value
			this.formData.propertyEntity.provinceName = data[0].label
      this.formData.propertyEntity.cityCode = data[1].value
      this.formData.propertyEntity.cityName = data[1].label
      this.formData.propertyEntity.countyCode = data[2].value
      this.formData.propertyEntity.countyName = data[2].label
      this.formData.propertyEntity.townshipCode = data[3].value
      this.formData.propertyEntity.townshipName = data[3].label
		},
		regionInit() {
      new this.$rest({
				gateway: 'agrobiz',
        service: "agrobiz-uc",
        url: "/v1.0/plus/union/region/lazy",
				query: {
					equal: {
            regionId: "0"
          }
				},
				action: (res)=>{
					if(res.data.code === 20000){
						const data = res.data.data
						this.regionArray = data
					} else {
						this.$Message.error({
              content: res.data.msg
            })
					}
				}
			}).get()
    },
		loadRegion(item, callback) {
			item.loading = true
			new this.$rest({
				gateway: 'agrobiz',
        service: "agrobiz-uc",
        url: "/v1.0/plus/union/region/lazy",
				query: {
					equal: {
            regionId: item.id,
            regionLevel: 4
          }
				},
				action: (res)=>{
					if(res.data.code === 20000){
						const data = res.data.data
						item.children = data
						item.loading = false
            callback()
					} else {
						this.$Message.error({
              content: res.data.msg
            })
					}
				}
			}).get()
		},
		Submit() {
			if(this.spuUploadList.length === 0) {
				this.$Notice.warning({
					title: '必填项为空',
					desc: `请上传商品图`
				})
				return false
			}
			this.seletions.forEach(element => {
				if(this.formData.orgId === element.orgId) {
					this.formData.orgName = element.orgName
				}
			})

			let goodsAlbum = []
			this.spuUploadList.forEach(element => {
				let album = new Object()
				album.src = element.src
				album.type = 0
				goodsAlbum.push(album)
			})
			this.formData.goodsAlbum = JSON.stringify(goodsAlbum)
			this.skuInfo.specEntityList = [
				{specName:'面积',specValue:this.formData.propertyEntity.propertyArea+this.skuInfo.skuUom}
			]
			this.skuInfo.skuImage = this.spuUploadList[0].src
			this.skuInfo.skuModel = Dict.propertyBelong.name(this.formData.propertyEntity.propertyBelong) 
				+ '/' + Dict.propertyType.name(this.formData.propertyEntity.propertyType)
				+ '/' + Dict.transferType.name(this.formData.propertyEntity.transferType)
			this.formData.skuList.length = 0
			this.formData.skuList.push(this.skuInfo)
			this.formData.spuImage = this.spuUploadList[0].src
			this.formData.spuArticle = this.editor.txt.html()
			this.formData.productionPlace = this.formData.propertyEntity.provinceName + this.formData.propertyEntity.cityName + this.formData.propertyEntity.countyName + this.formData.propertyEntity.townshipName + this.formData.productionPlace

			new this.$rest({
				gateway: 'agroerp',
				service: "agroerp-shop",
				url: '/v1.0/agromall/create/basic/sku',
				data: {
					pojo: this.formData,
				},
				action: (res) => {
					if (res.data.code === 20000) {
						this.callbank()
					} else {
						this.$Notice.warning({
							title: "操作失败",
							desc: `失败原因：${res.data.msg}`
						})
					}
				}
			}).post()
		},
		initEditor() {
			this.editor = new E('#editorContainer')
			this.editor.config.height = 800
			this.editor.config.placeholder = '项目详情介绍'
			this.editor.config.uploadImgServer = `${env_config.upload_config.api}/agrobiz-file/v1.0/upload/single/file/binary`
			this.editor.config.uploadImgMaxSize = 1 * 1024 * 1024
			this.editor.config.uploadImgMaxLength = 1
			this.editor.config.uploadFileName = 'binaryFile'
			this.editor.config.uploadImgParams = {
				catalog:'goods',
				selfName: false
			}
			this.editor.config.uploadImgHeaders = {
				'Authorization': 'Bearer ' + this.$store.getToken()
			}
			this.editor.config.uploadImgHooks = {
				success: (xhr)=>{
					console.log('图片插入成功',xhr)
				},
				fail: (xhr, editor, resData)=>{
					console.log('fail', resData)
					this.$Message.error('图片插入时出错')
				},
				error: (xhr, editor, resData)=>{
					console.log('error', xhr, resData)
					this.$Message.error('http请求异常')
				},
				timeout: (xhr)=>{
					console.log('timeout')
					this.$Message.error('上传超时')
				},
				customInsert: (insertImgFn, result)=>{
					console.log('result ->',result)
					if(result.code === 20000){
						insertImgFn(result.data.protocol + result.data.hostName+ result.data.filePath)
					} else {
						this.$Notice.error({
							title: '上传失败',
							desc: `原因：${result.msg}`
						})
					}
				}
			}
			this.editor.create()
		}
	},
	created(){
		
	},
	mounted() {
		this.spuUploadList = this.$refs.spu_upload.fileList;

		//初始化富文本编辑器
		this.initEditor()
	},
	beforeUnmount() {
		this.editor.destroy()
	}
}
</script>
<style lang="less" scoped>
table{
	th {
    border: 1px solid #ccc;
    min-width: 50px;
    height: 20px;
        background-color: yellow;
    }
}

h1 {
	background-color: #f5f5f5; font-size: 18px;
	padding: 10px;
	color: #333;
	margin-bottom: 18px;
}

.view-input {
	width: 100%;
}

.vertical-center-modal {
	display: flex;
	align-items: center;
	justify-content: center;
}

.demo-upload-list {
	display: inline-block;
	width: 60px;
	height: 60px;
	background: #fff;
	position: relative;
	margin-right: 4px;
}

.demo-upload-list img {
	width: 100%;
	height: 100%;
	border-radius: 4px;
	box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
}

.demo-upload-list-cover {
	display: none;
	position: absolute;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	background: rgba(0, 0, 0, .6);
}

.demo-upload-list:hover .demo-upload-list-cover {
	display: block;
}

.demo-upload-list-cover i {
	color: #fff;
	font-size: 20px;
	cursor: pointer;
	margin: 0 2px;
}

.intro-con {
	min-height: 140px;
}

.draggable-btn {
	margin-top: 20px;
}

.code-con {
	width: 400px;
	background: #F9F9F9;
	padding-top: 10px;
}

.goods-type div.box-in {
	border: 1px solid #d9c9c6;
	text-align: center;
	cursor: pointer;
	height: 60px;
	position: relative;
}

.goods-type div.box-in>img {
	width: 25%;
	height: 50%;
	position: absolute;
	bottom: 0;
	right: 0;
}

.category-params {
	background-color: #f5f5f5;
	padding: 10px;
}

.button-addSpec {
	width: 98%;
	background-color: #f5f5f5;
	margin: 10px auto;
	padding: 8px;
}
.spec-item {
	display: inline-block; vertical-align: top; position: relative;
}
.have-img {
	height: 110px;
}
.spec-item:hover .del-spec {
	display: block;
}
.spec-item .del-spec {
	position: absolute; top: -8px; right: 0; width: 20px; z-index: 99; opacity: .5; display: none; cursor: pointer;
}
.spec-item .ivu-upload {
	position: absolute; top: 40px; left: 22px;
}
.spec-img {
	margin-top: 5px;
}
.spec-img>img {
	width: 100px; height: 80px; border-radius: 5px; border: 2px solid #FFFFFF;
}
.spec-img>img:hover {
	box-shadow: 0 0 7px #00000050;
}
footer {
	position: fixed; width: auto; bottom: 25px; left: 200px; right: 0; text-align: center; z-index: 999999;
}

th .ivu-table-cell {
	white-space: nowrap;
}
.ivu-table-cell {
	white-space: nowrap;
}
.skuTab b {
	padding: 0 10px; cursor: pointer;
}
</style>
